package com.itheima.userdemo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
// /*拦截所有的请求
// *.jsp 拦截所有后缀是.jsp
//@WebFilter("/*")
public class FilterDemo implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("FilterDemo init,初始化，执行1次");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("FilterDemo-doFilter...start,只要符合规则就执行");
        // 是否可以打印，获取到请求的路径，请求的路径在什么对象中存储
        // URL 与  URI的区别
        // URL: http://localhost:8080/userdemo/loginServlet
        // URI: /userdemo/loginServlet
        HttpServletRequest req = (HttpServletRequest)request;
        String requestURI = req.getRequestURI();
        System.out.println(requestURI);

        // FilterChain过滤链 （链,资源链接)
        // 放行
        request.setCharacterEncoding("utf-8");
        // 继续执行下一个，不执行此语句，意味被拦截后，后续都不执行了。
        // 放行之前的逻辑
        chain.doFilter(request,response);
        // 放行之后（响应给前端）逻辑
        System.out.println("FilterDemo-doFilter...end");
    }

    @Override
    public void destroy() {
        System.out.println("FilterDemo destroy... 销毁，服务器重启或销毁，才执行");
    }
}
